package com.zh.note.leetcode.linkedList;

import com.zh.note.leetcode.model.ListNode;

/**
 * @Author: zhanghuan
 * @date: 2023/6/11 18:14
 * @description: create it
 */
public class LC_206_reverseList {

    public ListNode reverseList(ListNode head) {
        ListNode pre = null;
        ListNode cur = head;
        // 终止条件是cur == null 结束
        while (cur != null) {
            // 创建临时变量保存cur下一个节点
            ListNode temp = cur.next;
            cur.next = pre;
            // 必须先处理pre
            pre = cur;
            cur = temp;
        }
        return pre;

    }

    public ListNode reverseList2(ListNode head) {
        return reverse(null, head);
    }

    private ListNode reverse(ListNode pre, ListNode cur) {
        if (cur == null) {
            return pre;
        }
        ListNode temp = cur.next;
        cur.next = pre;
        return reverse(cur, temp);
    }
}
